//
//  BKUserAccount.swift
//  微博
//
//  Created by mac on 16/8/11.
//  Copyright © 2016年 xbk. All rights reserved.
//

import UIKit

class BKUserAccount: NSObject,NSCoding{
    
    var access_token :String?
    
    //assess_token的生命周期
    var expires_in :NSTimeInterval = 0 {
    
        didSet {
        
            //过期时间 = 获取accestoken的时间 + 生命周期
            expiresDate = NSDate().dateByAddingTimeInterval(expires_in)
        }
    }
    
    //过期时间
    var expiresDate :NSDate?

    var uid:Int64 = 0

    //  用户名
    var name: String?
    //  头像
    var avatar_large: String?
    
    //kvc构造函数
    init(dic:[String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dic)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    //重写description方法
    override var description :String {
    
        let keys = ["access_token", "expires_in", "uid", "name", "avatar_large"]
        
        return dictionaryWithValuesForKeys(keys).description
    }
    
    //归档
    func encodeWithCoder(aCoder: NSCoder) {
        
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeInt64(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    required init?(coder aDecoder: NSCoder) {
        
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeInt64ForKey("uid")
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    
    //调用该方法保存用户对象到指定沙盒路径
    func saveUserAccount () {
    
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!as NSString).stringByAppendingPathComponent("userAccount.archive")
        
        //执行归档
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
        
        print(path)
    }
    //类函数
    class func loadUserAccount() ->BKUserAccount? {
        
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.archive")

        return NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? BKUserAccount
    }
    
}
